package net.example.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import net.example.activity.adapter.HeaderAdapter;
import net.example.activity.adapter.KeyValuePairAdpter;
import net.example.manager.ClientGlobalCache;
import net.example.manager.Manager;
import net.example.model.Group_Friend_SelectorType;
import net.example.model.KeyValuePairModel;
import net.example.model.GGGroup;
import net.example.model.GGUser;
import net.example.model.UpdatePropertyType;
import net.example.model.UserBasicModel;
import net.example.model.event.GroupInfoChangedEvent;
import net.example.model.event.GroupUserChangedEvent;
import net.example.ggtalk.R;
import net.example.utils.IntentUtils;
import net.example.utils.ToastUtils;
import net.example.utils.android.AndroidUI;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class GroupDetailActivity extends Activity implements AdapterView.OnItemClickListener {

    private String groupID;
    private GGGroup group;
    private boolean isCreator;
    private boolean isGroupMember;
    private String operateMsg;
    private GridView gridView;
    private List<UserBasicModel> userBasicModelList;
    private List<KeyValuePairModel> modelList;
    private KeyValuePairAdpter adpter;
    private HeaderAdapter gridAdapter;
    private Button delBtn;
    TextView title;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        groupID=getIntent().getStringExtra("requestID");
        title=(TextView)findViewById(R.id.headerText) ;
        delBtn= (Button) findViewById(R.id.btn_del);
        this.setBaseInfo();

        this.initGridView();
        this.initListView();
    }
    @Override
    protected void onResume()
    {
        super.onResume();
    }

    private void initGridView()
    {
        gridView=(GridView) findViewById(R.id.group_detail_gridView);
        List<GGUser> userList= Manager.getInstance().getGGUserByGroupID(groupID);
        userBasicModelList =this.GGUserListConvertToUserBasicModel(userList);
        gridAdapter=new HeaderAdapter(userBasicModelList,GroupDetailActivity.this);
        gridView.setAdapter(gridAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> adapterView,View view,int position,long id)
            {
                if (group.IsPrivate)//私密群不能查看用户详情
                {
                    return;
                }
                String userID=userBasicModelList.get(position).getUserID();
                if(userID.equals("+")){
                    Intent intent = new Intent(GroupDetailActivity.this, Group_Friend_SelectorActivity.class);
                    intent.putExtra("groupFriendSelectorType", Group_Friend_SelectorType.PullMemberInGroup);
                    intent.putExtra("groupID",groupID);
                    GroupDetailActivity.this.startActivity(intent);
                }
                else if(userID.equals("-")){
                    Intent intent = new Intent(GroupDetailActivity.this, Group_Friend_SelectorActivity.class);
                    intent.putExtra("groupFriendSelectorType", Group_Friend_SelectorType.TickMemberOutGroup);
                    intent.putExtra("groupID",groupID);
                    GroupDetailActivity.this.startActivity(intent);
                }
                else if(userID.equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID()))
                {
                    Intent intent = new Intent(GroupDetailActivity.this, MainActivity.class);
                    intent.putExtra("tabID", R.id.btn_main_setting);
                    startActivity(intent);
                }
                else {
                    net.example.utils.android.IntentUtils.startActivityForString(GroupDetailActivity.this ,UserDetailActivity.class,"requestID",userID);
                }
            }
        });
    }

    private List<UserBasicModel> GGUserListConvertToUserBasicModel(List<GGUser> GGUsers)
    {
        List<UserBasicModel> models=new ArrayList<>();
        if(GGUsers !=null&& GGUsers.size()>0)
        {
            for (GGUser GGUser : GGUsers) {
                models.add(new UserBasicModel(GGUser.getUserID(), GGUser.getName(), GGUser.getCommentName()));
            }
        }
        if(!this.group.IsPrivate)//私密群不能修改群人员
        {
            this.addOperateModel(models);
        }
        ViewGroup.LayoutParams layoutParams=gridView.getLayoutParams();
        if(models.size()>=20)
        {
            layoutParams.height= AndroidUI.Dp2Px(this,300);
        }
        else {
            layoutParams.height=ViewGroup.LayoutParams.WRAP_CONTENT;
        }
        gridView.setLayoutParams(layoutParams);
        return models;
    }

    //增加操作按钮
    private void addOperateModel(List<UserBasicModel> models)
    {
//        group_header_item
        if(isGroupMember)
        {
            models.add(new UserBasicModel("+","",R.drawable.addto_btn));
        }
       if(isCreator)
       {
           models.add(new UserBasicModel("-","",R.drawable.reduce_btn));
       }
    }

    private void initListView()
    {
        ListView listView=(ListView) findViewById(R.id.listview_group_1);
        modelList=new ArrayList<KeyValuePairModel>();
        adpter=new KeyValuePairAdpter(modelList,this);
        listView.setAdapter(adpter);
        listView.setOnItemClickListener(this);
        this.getModelList();
    }

    private void getModelList() {
        modelList.clear();
        group = ClientGlobalCache.getInstance().getGroup(groupID);
        modelList.add(new KeyValuePairModel(getResources().getString(R.string.group_id), groupID, false));
        modelList.add(new KeyValuePairModel(getResources().getString(R.string.group_creatorName), ClientGlobalCache.getInstance().getUser(group.getCreatorID()).getName(), false));
        modelList.add(new KeyValuePairModel(getResources().getString(R.string.group_type), group.IsPrivate ? "密聊群" : "普通群", false));
        modelList.add(new KeyValuePairModel(getResources().getString(R.string.group_name), group.getName(), this.isCreator));
        modelList.add(new KeyValuePairModel(getResources().getString(R.string.group_announce), group.getAnnounce(), this.isCreator));
        adpter.notifyDataSetChanged();
    }

    public void finish(View view) {
        finish();
    }

    public void clickBtn(View view)
    {
        if(!this.isGroupMember){
            Intent intent = new Intent(GroupDetailActivity.this, AddFriendOrGroupApplyActivity.class);
            intent.putExtra("friendID", groupID);
            intent.putExtra("isGroup", true);
            this.startActivity(intent);
//            IntentUtils.startActivityForString(GroupDetailActivity.this, AddFriendOrGroupApplyActivity.class,"friendID",groupID,"isGroup",true);
            return;
        }
        showNormalDialog();
    }

    //弹出提示框
    private void showNormalDialog() {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(GroupDetailActivity.this);
        normalDialog.setTitle("提示");
        normalDialog.setMessage(String.format("您确定要%s[%s]吗？", operateMsg, this.group.getName()));
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(isCreator)
                        {
                            Manager.getInstance().deleteGroup(groupID);
                            ToastUtils.showShort(GroupDetailActivity.this,"解散成功");
                        }else {
                            Manager.getInstance().quitGroup(groupID);
                        }
                        IntentUtils.startActivity(GroupDetailActivity.this, MainActivity.class);
                    }
                });

        // 显示
        normalDialog.show();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        if(!isCreator)
        {
            return;
        }
        KeyValuePairModel model=this.modelList.get(position);
        try {
            if(model.Key.equals(getResources().getString(R.string.group_name)))
            {
                /// TO DO 修改群名称
                IntentUtils.startActivityForString_Dubble(this,UpdatePropertyActivity.class, getResources().getString(R.string.update_property_type), UpdatePropertyType.GroupName.toString(),
                        getResources().getString(R.string.property_entity),JSON.toJSONString(group));
            }
            else if(model.Key.equals(getResources().getString(R.string.group_announce)))
            {
                IntentUtils.startActivityForString_Dubble(this,UpdatePropertyActivity.class, getResources().getString(R.string.update_property_type), UpdatePropertyType.GroupAnnounce.toString(),
                        getResources().getString(R.string.property_entity),JSON.toJSONString(group));
            }
        }catch (Exception ee) {
            ee.printStackTrace();
        }

    }

    public void onEventMainThread(GroupInfoChangedEvent event)
    {
        if (groupID.equals(event.groupID)) {
            this.setBaseInfo();
            this.getModelList();
        }
    }

    public void onEventMainThread(GroupUserChangedEvent event)
    {
        if(event.groupID.equals(this.groupID))
        {
            this.setBaseInfo();
            this.userBasicModelList.clear();
            List<GGUser> userList= Manager.getInstance().getGGUserByGroupID(groupID);
            userBasicModelList.addAll(this.GGUserListConvertToUserBasicModel(userList));
            this.gridAdapter.notifyDataSetChanged();
        }
    }

    private void setBaseInfo()
    {
        group = ClientGlobalCache.getInstance().getGroup(groupID);
        if (group != null) {
            title.setText(group.getName() + "(" + group.getChildCount() + "人)");
        } else {
            title.setText(groupID + "(" + 0 + ")");
        }
        this.isGroupMember=group.getChildMemberList().contains(ClientGlobalCache.getInstance().getCurrentUser().getUserID());
        if(!this.isGroupMember){operateMsg="加入讨论组";}
        else {
            isCreator= this.group.getCreatorID().equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID());
            operateMsg = isCreator ? "解散讨论组" : "退出讨论组";
        }
        delBtn.setText(operateMsg);
    }

    @Override
    protected void onDestroy()
    {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
